package com.bruce.ai.alibaba.agentcard.register.service;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import jakarta.annotation.PreDestroy;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * Agent 服务注册服务
 * 负责将 Agent 服务注册到 Nacos
 */
@Service
public class AgentRegistrationService {

    private static final Logger logger = LoggerFactory.getLogger(AgentRegistrationService.class);

    @Autowired
    private NamingService namingService;

    @Autowired
    private A2AAgentRegistrationService a2aAgentRegistrationService;

    @Value("${server.port:8080}")
    private int serverPort;

    @Value("${agent.service-name:asurada-agent}")
    private String serviceName;

    @Value("${agent.cluster-name:DEFAULT}")
    private String clusterName;

    @Value("${agent.weight:1.0}")
    private double weight;

    @Value("${agent.description:Asurada Agent for A2A communication}")
    private String description;

    @Value("${agent.version:1.0.0}")
    private String version;

    @Value("${agent.skills:general,testing}")
    private String skills;

    private String localIp;

    /**
     * 应用启动完成后自动注册服务
     */
    @EventListener(ApplicationReadyEvent.class)
    public void registerAgent() {
        try {
            // 1. 传统的 Nacos 服务注册
            registerTraditionalService();
            
            // 2. A2A Agent 注册
            registerA2AAgent();
            
        } catch (Exception e) {
            logger.error("Failed to register agent", e);
        }
    }

    /**
     * 传统的 Nacos 服务注册
     */
    private void registerTraditionalService() {
        try {
            // 获取本机IP地址
            localIp = getLocalIpAddress();
            
            // 创建服务实例
            Instance instance = new Instance();
            instance.setIp(localIp);
            instance.setPort(serverPort);
            instance.setWeight(weight);
            instance.setHealthy(true);
            instance.setEnabled(true);
            instance.setClusterName(clusterName);
            
            // 设置实例元数据
            Map<String, String> metadata = new HashMap<>();
            metadata.put("description", description);
            metadata.put("version", version);
            metadata.put("skills", skills);
            metadata.put("agentcard-url", "http://" + localIp + ":" + serverPort + "/agentcard");
            metadata.put("a2a-endpoint", "http://" + localIp + ":" + serverPort + "/a2a/call");
            metadata.put("provider", "Asurada");
            instance.setMetadata(metadata);
            
            // 注册服务实例
            namingService.registerInstance(serviceName, instance);
            
            logger.info("Traditional service registered successfully: {}:{}:{}", serviceName, localIp, serverPort);
            logger.info("Agent metadata: {}", metadata);
            
        } catch (Exception e) {
            logger.error("Failed to register traditional service", e);
        }
    }

    /**
     * A2A Agent 注册
     */
    private void registerA2AAgent() {
        try {
            boolean success = a2aAgentRegistrationService.registerA2AAgent();
            if (success) {
                logger.info("A2A Agent registration completed successfully!");
                
                // 验证 AgentCard 是否在 Nacos 中可见
                logger.info("Verifying AgentCard visibility in Nacos A2A Registry...");
                if (a2aAgentRegistrationService.verifyAgentCardVisibility()) {
                    logger.info("AgentCard verification successful - Agent is visible in A2A Registry!");
                } else {
                    logger.warn("AgentCard verification failed - Agent may not be visible in A2A Registry");
                }
            } else {
                logger.error("A2A Agent registration failed!");
            }
        } catch (Exception e) {
            logger.error("Failed to register A2A agent", e);
        }
    }

    /**
     * 应用关闭时注销服务
     */
    @PreDestroy
    public void deregisterAgent() {
        try {
            if (localIp != null) {
                // 注销传统服务
                namingService.deregisterInstance(serviceName, localIp, serverPort);
                logger.info("Traditional service deregistered successfully: {}:{}:{}", serviceName, localIp, serverPort);
                
                // 注意：A2A Agent 的注销通常由 Nacos 自动处理，或者需要调用特定的注销 API
                // 这里可以根据需要添加 A2A Agent 的注销逻辑
                logger.info("A2A Agent deregistration completed (handled by Nacos automatically)");
            }
        } catch (Exception e) {
            logger.error("Failed to deregister agent", e);
        }
    }

    /**
     * 获取本机IP地址
     */
    private String getLocalIpAddress() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }

    /**
     * 检查服务注册状态
     */
    public boolean isServiceRegistered() {
        try {
            return namingService.getAllInstances(serviceName).stream()
                    .anyMatch(instance -> instance.getIp().equals(localIp) && instance.getPort() == serverPort);
        } catch (NacosException e) {
            logger.error("Failed to check service registration status", e);
            return false;
        }
    }
}